package com.xyz.business.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.xyz.base.action.PageAction;
import com.xyz.business.bean.User;
import com.xyz.business.service.UserService;
import com.xyz.business.service.impl.UserHelper;
import com.xyz.constant.XYZConstant;
import com.xyz.init.infos.UserInfosInit;

/**
 * 用户Action
 * 
 * @author xyzjh
 * 
 */
public class UserAction extends PageAction {
	/**
	 * 序列号
	 */
	private static final long serialVersionUID = -4478604145628049267L;
	/**
	 * 日志类
	 */
	private Logger log = Logger.getLogger(UserAction.class);
	/**
	 * 用户信息
	 */
	private User user;
	/**
	 * 用户列表
	 */
	private List<User> users;
	/**
	 * 新增标志
	 */
	private int addFlag;
	/**
	 * 服务类
	 */
	private UserService userService;
	/**
	 * ajax返回结果
	 */
	private String message;

	// /**
	// * 新建用户
	// *
	// * @return
	// */
	// public String insert() {
	// log.info("insert begin...");
	// UserAddResponse response = userService.insert(user);
	// // 成功
	// if (response.getReturnCode().equals("0000")) {
	// return SUCCESS;
	// } else {
	// getRequest().setAttribute("message", "新增用户失败");
	// return INPUT;
	// }
	//
	// }

	/**
	 * 显示新增页面、点击修改显示详细
	 * 
	 * @return
	 */
	public String add() {
		Map<Integer, String> userTypeMap = UserHelper.getUserTypeMapp();
		getRequest().setAttribute("userTypeMap", userTypeMap);
		// 点击页面修改时，会穿一个uid进来
		if (null != user && !StringUtils.isBlank(user.getUid())) {
			// uid不为空
			List<User> userList = getUserList();

			user = (null == userList || userList.size() == 0) ? user : userList
					.get(0);
		}

		return SUCCESS;
	}

	/**
	 * 修改、新增
	 * 
	 * @return
	 */
	public String synAddMod() {
		// 新增
		if (StringUtils.isBlank(user.getUid())) {
			// 获取登录用户信息
			User loginUser = (User) getRequest().getSession().getAttribute(
					"login_user");

			// 不能新增管理员
			if (loginUser.getType() == XYZConstant.ADMIN_CODE) {
				log.info("普通用户不能新增管理员");
				message = "1";
			} else {
				// 非管理员不能新增
				if (loginUser.getType() != XYZConstant.ADMIN_CODE
						&& loginUser.getType() == XYZConstant.SYSTEM_USER) {
					log.info("普通用户不能新增管理员");
					message = "1";
				} else {
					try {
						userService.insertUser(user);
						message = "0";
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						log.error("新增用户发生异常：" + e);
						message = "1";
					}
				}

			}

		}
		// // 修改
		else {
			try {
				userService.updateUser(user);
				message = "0";
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				log.error("修改用户发生异常：" + e);
				message = "1";
			}
		}
		UserInfosInit.init(userService);
		return SUCCESS;
	}

	/**
	 * 显示用户列表
	 * 
	 * @return
	 */
	public String userPage() {
		//
		Map<Integer, String> userTypeMap = UserHelper.getUserTypeMapp();
		getRequest().setAttribute("userTypeMap", userTypeMap);

		List<User> userList = getUserList();
		getRequest().setAttribute("userList", userList);
		return SUCCESS;
	}

	public List<User> getUserList() {
		//
		List<User> userList = new ArrayList<User>(32);
		try {
			setRowCount(userService.queryUserCount(user));
			baseDeal();
			// setPageSize(reportService.queryReportCount(report, enterprise));
			userList = userService.query(user, (getPageNow() - 1)
					* getPageSize(), getPageSize());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.error(" cathc one exception when query:" + e);
		}
		return userList;
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	public String register() {
		log.info("register begin...");
		int isLoginNameExit;
		String mess = XYZConstant.EMPTY;
		String result = "input";
		if (user.getRepetpassword().equals(user.getPassword())) {
			try {
				isLoginNameExit = userService.queryUserByName(user
						.getLoginname());

				if (isLoginNameExit <= 0) {
					userService.insertUser(user);
					mess = "注册成功.";
					result = SUCCESS;
				} else {
					mess = "注册的用户名已存在，请更改用户名.";
				}
			} catch (SQLException e) {
				log.error("catch one SQLException:" + e);
				mess = "系统错误.";
				e.printStackTrace();
			}
		} else {
			mess = "两次密码输入不一致.";
		}

		getRequest().setAttribute("mess", mess);
		return result;
	}

	/**
	 * 登录
	 * 
	 * @return
	 */
	public String login() {
		log.info("login begin...");
		String result = "input";
		String mess = XYZConstant.EMPTY;
		try {
			User user2 = userService.queryUser(user.getLoginname());
			if (null != user2) {
				int isUserExit = userService.login(user);
				if (isUserExit > 0) {
					result = SUCCESS;
					HttpSession session = getRequest().getSession();
					session.setAttribute("login_user", user2);
					// session失效30分钟
					session.setMaxInactiveInterval(30 * 60);
				} else {
					mess = "登录密码输入错误.";
				}
			} else {
				mess = "登录用户名不存在.";
			}
		} catch (SQLException e) {
			log.error("catch one SQLException:" + e);
			mess = "系统错误.";
		} catch (Exception e) {
			log.error("catch one Exception:" + e);
			mess = "系统错误.";
		}
		getRequest().setAttribute("mess", mess);
		return result;
	}

	public String loginout() {

		log.info("loginout begin...");
		HttpSession session = getRequest().getSession(false);
		if (session != null) {
			session.invalidate();
		}
		return SUCCESS;
	}

	public String query() {
		// int pageSize = getRows();
		//
		// int pageNow = getPage();
		// if (form == null) {
		// form = new UserForm();
		// }
		// form.setPageNow(pageNow);
		// form.setPageSize(pageSize);
		// log.info(" query begin...");
		// UserQueryResponse response = userService.query(form);
		// Map<String, Object> jsonMap = new HashMap<String, Object>();
		// // ui需要显示数据的总页数
		//
		// jsonMap.put("total", response.getRowCount());
		//
		// // ui需要实现数据的总记录数
		// jsonMap.put("rows", response.getUserList());
		//
		// setResult(JSONObject.fromObject(jsonMap));
		//
		// // setPageCount(response.getPageCount());
		// // setUsers(response.getUserList());
		return SUCCESS;
	}

	/**
	 * 删除用户（实际为隐藏）
	 * 
	 * @return
	 */
	public String delete() {
		try {
			userService.hideUser(user.getUid());
		} catch (SQLException e) {
			log.error("隐藏用户失败");
		}
		
		UserInfosInit.init(userService);
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public int getAddFlag() {
		return addFlag;
	}

	public void setAddFlag(int addFlag) {
		this.addFlag = addFlag;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}
